package com.csproj.example.resource;

import com.codahale.metrics.annotation.Timed;
import com.csproj.example.service.OrganizationService;
import com.csproj.example.service.dto.OrganizationDTO;
import com.csproj.siiat.base.common.dto.BaseDTO;
import com.csproj.siiat.base.common.repository.PageableTools;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 机构管理的resource
 *
 *  TODO action、service都秉承返回是什么资源就在那个资源的aciton、service里面写（比如查看uid=3的机构信息）
 *  TODO url定义遵循/api/gateway（服务名）/v1/资源名
 *  TODO 定义rap要理解资源的概念（比如图书馆的书和我借的书）
 *
 *  TODO action方法只负责控制调用，不处理具体业务。
 */
@RestController
@RequestMapping("/api/siiat/v1")
public class OrganizationResource {

    private final Logger log = LoggerFactory.getLogger(OrganizationResource.class);

    private static final String ENTITY_NAME = "organization";

    private final OrganizationService organizationService;

    public OrganizationResource(OrganizationService organizationService){
        this.organizationService = organizationService;
    }

    /**
     * POST  /organizations : 创建机构.
     * @param organizationDTO 机构DTO
     * @return
     * TODO 保存post方法
     * TODO 每个方面里面都要加try catch处理
     */
    @PostMapping("/organizations")
    @Timed
    public BaseDTO createOrganization(@Valid @RequestBody OrganizationDTO organizationDTO){
        OrganizationDTO result = organizationService.saveAndGetDTO(organizationDTO);
        return BaseDTO.createBaseDTO().setData(result);
    }

    /**
     * PUT  /organizations : 修改机构信息.
     * @param organizationDTO 机构DTO
     * @return
     */
    @PutMapping("/organizations/{id}")
    @Timed
    public BaseDTO updateOrganization(@Valid @RequestBody OrganizationDTO organizationDTO, @PathVariable String id) throws URISyntaxException {
        organizationDTO.setId(id);
        OrganizationDTO result = organizationService.updateAndGetDTO(organizationDTO);
        return BaseDTO.createBaseDTO().setData(result);
    }

    /**
     * GET  /organizations : 获取机构信息.
     * @return 机构信息
     */
    @GetMapping("/organizations/all")
    @Timed
    public BaseDTO getAllOrganizations() {
        List<OrganizationDTO> organizations = organizationService.findAllAndGetDTO();
        return BaseDTO.createBaseDTO().setFieldList(organizations);
    }

    /**
     * GET  /organizations : 获取机构信息.
     * @return 机构信息
     */
    @GetMapping("/organizations")
    @Timed
    public BaseDTO getPageOrganizations(@RequestParam(value = "pageNumber",required = false) Integer pageNum,
                                        @RequestParam(value = "name",required = false) String name) {
        Pageable pageable = PageableTools.basicPage(pageNum);
        Map<String,Object> map = new HashMap<>();
        if (StringUtils.isNotBlank(name)) {
            map.put("name",name);
        }
        BaseDTO result = organizationService.findPageListAndGetDTO(map,pageable);
        return result;
    }

    /**
     * GET  /organizations/:id : 根据机构id，获取机构信息
     *
     * @param id 机构id
     * @return 机构信息
     */
    @GetMapping("/organizations/{id}")
    @Timed
    public BaseDTO getOrganization(@PathVariable String id) {
        OrganizationDTO organizationDTO = organizationService.findOneAndGetDTO(id);
        return BaseDTO.createBaseDTO().setData(organizationDTO);
    }

    /**
     * DELETE  /organizations/:id : 根据id，删除机构信息.
     * @param id id
     * @return
     */
    @DeleteMapping("/organizations/{id}")
    @Timed
    public BaseDTO deleteOrganization(@PathVariable String id) {
        organizationService.delete(id);
        return BaseDTO.createBaseDTO().setMessage("删除机构成功！");
    }

    /**
     * 根据机构ids，批量删除机构信息
     * @param ids ids
     * @return
     */
    @DeleteMapping("/organizations/deleteOrganizations")
    @Timed
    public BaseDTO deleteIds(@RequestBody(required = false) String[] ids) {
        organizationService.deleteIds(ids);
        return BaseDTO.createBaseDTO().setMessage("批量删除机构成功！");
    }

    /**
     * 上传文件
     * @param file file
     * @return
     */
    @PostMapping("/organizations/uploadFile")
    @Timed
    public BaseDTO uploadFile(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        String filePath = organizationService.uploadFile(request,file);
        Map<String,Object> map = new HashMap<>();
        map.put("url",filePath);
        return BaseDTO.createBaseDTO(map).setMessage("上传文件成功！");
    }
}
